<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in" ref="applyHeight">
      <div class="cornerComment-in-title">
        <span>调查问卷详情</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody editDetail">
        <el-form ref="infoForm" :model="infoForm" label-width="140px">
          <el-form-item label="问卷标题:" prop="title">
            <p>{{ infoForm.title }}</p>
          </el-form-item>
          <el-form-item label="问卷描述:" prop="description">
            <p v-html="infoForm.description?infoForm.description:'无'"></p>
          </el-form-item>
          <el-form-item label="承诺书:" prop="commitment">
            <div>
              <el-button @click="commitmentBtnFn" size="small" class="ml-20" v-if="infoForm.commitment">展示承诺书
              </el-button>
              <span v-else>无</span>
            </div>
          </el-form-item>
          <el-form-item label="家长签字:" prop="is_sign">
            <div>
              {{ infoForm.is_sign ? '是' : '否' }}
            </div>
          </el-form-item>
          <el-form-item label="查看人员:" prop="is_sign" v-if="editBody && editBody.see">
            <el-tag
                v-for="item in editBody.see"
                :key="item.id"
                type="mini"
                effect="plain">
              {{ item.realname }}
            </el-tag>
          </el-form-item>
          <el-form-item label="问卷范围:" prop="title">
            <div>
              <span v-if="infoForm.type==0">全校</span>
              <span v-if="infoForm.type==1">特定年段(<span v-for="(item,index) in editsection_id"
                                                       :key="index">{{ item.section_name }}</span>)</span>
              <span v-if="infoForm.type==2">特定班级(<span v-for="(item,index) in editClass_id"
                                                       :key="index">{{ item.class_name }}</span><span
                  v-if="editBody.student_id">,特定学生</span>)</span>
              <span v-if="infoForm.type==2&&editBody.student_id" style="display: block;">
                  <el-tag
                      :key="index"
                      v-for="(tag,index) in editBody.student_id"
                      class="mr-10"
                  >{{ tag.name }}
                  </el-tag>
                </span>
            </div>
          </el-form-item>
          <el-form-item label="问卷时间:" prop="end_time">
            <p>{{ infoForm.start_time }}至{{ infoForm.end_time }}</p>
          </el-form-item>
          <el-form-item label="问卷内容:">
            <div>
              <el-alert
                  title="导出全部明细为本问卷全部明细。本班/代理导出如果用户有代理多个班级，需要选择班级进行导出特定班级明细"
                  type="warning"
                  :closable="false">
              </el-alert>
              <el-button @click="gotoExcelAll(1)" class="mb-10" size="mini" type="primary" plain>
                导出问卷全部明细
              </el-button>
              <el-button @click="gotoExcelAll(2)" class="mb-10" size="mini" v-if="showDownStatus">
                导出问卷本班/代理班级明细
              </el-button>

              <div v-for="(items,index) in listCheck" class="question-list">
                <!--v-if="items.show_status"-->
                <p class="questionTitle"><em>{{ index + 1 }}.</em>{{ items.content }}
                  {{items.classes?`【${items.classes.class_name}】`:''}}
                  <span class="showWordList" @click="showUserQulityFn(items.id)">(查看家长选项明细)</span>
                  <el-button @click="gotoExcel(index, 1)" class="mb-10" size="mini" type="primary" plain>导出题目内容明细
                  </el-button>
                  <el-button @click="gotoExcel(index, 2)" class="mb-10" size="mini" v-if="showDownStatus">
                    导出题目本班/代理班级明细
                  </el-button>
                </p>
                <div class="question-list-option">
                  <div v-if="items.type!==3">
                    <div v-for="(line,indexs) in items.option" class="inlinebox">
                      <p>{{ line.index }}.{{ line.text }} <span>({{ line.number }}票)</span>
                      </p>
                      <el-button @click="gotoExcelOnly(line,items.id,items.content, 1)" class="ml-10" size="mini"
                                 type="primary" plain v-if="line.number">
                        导出单项内容明细
                      </el-button>
                      <el-button @click="gotoExcelOnly(line,items.id,items.content, 2)" class="ml-10" size="mini"
                                 v-if="showDownStatus && line.number">
                        导出单项本班/代理班级明细
                      </el-button>
                    </div>
                  </div>
                  <div class="inlinebox" v-else>
                    <p>用户自行输入</p>
                    <p class="showuserAnswer">用户提交项：<span v-for="useroption in items.option">（{{ useroption }}）</span>
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click.native="closePOpup" size="small">返回</el-button>
        <!--        <el-button size="small" type="primary" @click="onSubmit">修改并保存</el-button>-->
      </div>
    </div>
    <qustionUser :visible.sync="qustionUserVisible" :optionId="optionId"></qustionUser>
    <agentClassList :visible.sync="agentListVisible" :agentList="agentList"
                    @getClassDown="getClassDown"></agentClassList>
    <commitment :visible.sync="commitmentVisible" @commitmentEditFn="commitmentEditFn" :editId="editId"
                :commitment="infoForm.commitment"></commitment>
  </div>
</template>

<script>
import {questionDetail, questionEdit} from '@/api/admin/parents_questionnaire'
import {yeartime} from '@/assets/js/common'
import qustionUser from '@/components/dialog/qustionUser.vue'
import {mapActions, mapGetters} from "vuex";
import {agentClassIndex} from "@/api/admin/users"
import agentClassList from "./agentClassList";
import commitment from '@/components/dialog/commitment.vue'

export default {
  props: ['visible', 'detailId'], // tabValue 任务类型
  components: {
    qustionUser,
    agentClassList,
    commitment
  },
  data() {
    return {
      dialogVisible: false,
      qustionCheck: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      editorOption: {
        modules: {
          toolbar: [['bold', 'underline', 'color', 'clean', 'image']]
        }
      },
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      dialogTableVisible: false,
      infoForm: {
        body: [{
          'content': null,
          'type': '1',
          'show_status': 0,
          'option': [{text: '', type: '2', is_commitment: '0'}]
        }],
        title: '',
        class_id: '',
        section_id: '',
        type: 0,
        description: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        student_id: 0,
        is_sign: 0,
        commitment: '' // 承诺书
      },
      commitment: 0, // 承诺书 0否 1是
      commitmentVisible: false,
      qustionUserVisible: false,
      arryList: null,
      usersName: null,
      editId: this.$route.query.editId,
      listCheck: [],
      value1: [],
      sectionList: [],
      classesList: [],
      oldClass: {}, // 未处理的班级
      oldsection: {}, // 未处理的年段
      editClass_id: [],
      editsection_id: [],
      studentRadio: 0,
      studentVisible: false,
      dynamicTags: [],
      dynamicTagsId: [],
      dynamicTagsArray: {},
      editBody: null,
      optionId: 0,
      showDownStatus: false,
      agentUserClassId: 0,
      agentList: [],
      agentListVisible: false,
      quectionIndex: 0,
      quectionOption: null
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        this.InitFn()
      } else {
        this.clearFn()
      }
    }
  },
  created() {

  },
  methods: {
    clearPageData() {
      this.editForm = null
      this.canCheckBtn = false
    },
    // 详情数据
    InitFn() {
      questionDetail({id: this.detailId}).then(response => {
        console.log('问卷详情数据：', response)
        if (response.code === 0) {
          this.infoForm.start_time = response.vo.start_time
          this.infoForm.end_time = response.vo.end_time
          this.infoForm.title = response.vo.title
          this.listCheck = response.list
          this.infoForm.type = response.vo.type
          this.infoForm.class_id = response.vo.class_id
          this.infoForm.description = response.vo.description
          this.infoForm.commitment = response.vo.commitment
          this.infoForm.is_sign = response.vo.is_sign
          // 0全校 1特定年段 2特定班级
          if (Number(response.vo.type) === 1) {
            this.editsection_id = response.vo.section_id
          } else if (Number(response.vo.type) === 2) {
            this.editClass_id = response.vo.class_id
          }
          this.editBody = response.vo
          this.detailCheckFn()
          this.getAgentList() // 获取代理班级
        } else {
        }
      })
    },
    detailCheckFn() {
      console.log('listCheck', this.listCheck)
      for (let i in this.listCheck) {
        let option = this.listCheck[i]
        this.$fetch(this.api.questionnaire_option, {id: this.listCheck[i].id}).then((response) => {
          if (response.code === 0) {
            for (let j in response.list) {
              // type  1 是 2 否
              if (this.listCheck[i].type !== 3) {
                option.option[j].number = response.list[j].number
                if (Number(option.option[j].type) === 1) {
                  option.option[j].content = response.list[j].content
                }
              } else {
                option.option = response.list[j].content
              }
            }
            this.$set(this.listCheck, i, option)
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 获取代理班级，判断下载班级按键显示 showDownStatus
    getAgentList() {
      // 判断用户身份 showDownStatus 显示 agentUserClassId 对应班级id
      // 下载对应班级需要在班级问卷中，有代理班级身份
      console.log('用户身份，', this.userInfo)
      let question_type = Number(this.editBody.type); // 0 全校 1 特定年段 2 特定班级
      let n = this
      agentClassIndex({user_id: this.userInfo.id, p: 1}).then(res => {
        console.log('代理班级：', res, this.userInfo)
        // class_id section_id is_teacher 0 否 1 是 ；type 0班主任1带班老师2其他
        let list = []
        let need_list = [] // 特定班级，特定年段id
        for (let item of res.list.data) {
          list.push(item.classes)
        }
        this.agentList = list
        if (question_type === 0) {
          // 老师 代理老师可以下载按钮
          if (!Number(this.userInfo.is_teacher) && res.list.length) {
            n.showDownStatus = true
          }
          // 只有班主任 带班老师可以进行导出
          if (Number(this.userInfo.is_teacher) && (!Number(this.userInfo.type) || Number(this.userInfo.type) === 1)) {
            n.showDownStatus = true
            n.agentList.push(n.getJson(n.userInfo.class))
          }
        } else if (question_type === 1) {
          // 特定的年段老师代理老师可以下载 editsection_id 特定年段 editClass_id 特定班级
          for (let item of this.editsection_id) {
            if (n.userInfo.section_id === item.id) {
              n.showDownStatus = true
            }
          }
        } else if (question_type === 2) {
          // 特定的班级老师代理老师可以下载
          for (let item of this.editClass_id) {
            need_list.push(item.id)
            console.log('need_list:', need_list)
            if (n.userInfo.class_id === item.id) {
              n.showDownStatus = true
            }
          }
        }
        if (question_type === 1 || question_type === 2) {
          let agent_id = []
          for (let item of this.agentList) {
            agent_id.push(item.id)
            if (question_type === 2 && need_list.indexOf(item.id) !== -1) {
              n.showDownStatus = true
            }
          }
          if (Number(this.userInfo.is_teacher) && agent_id.indexOf(n.userInfo.class_id) === -1) {
            n.agentList.push(n.userInfo.class)
          }
        }
        console.log('特定信息：', this.editsection_id, this.editClass_id)
      })
    },
    commitmentBtnFn() {
      this.commitmentVisible = true
    },
    // 查看明细
    showUserQulityFn(id) {
      console.log('查询id：', id)
      this.optionId = id
      this.qustionUserVisible = true
    },
    // 单个题目
    gotoExcel(index, type, class_id, content) {
      if (type === 1) {
        this.gotoExcelHttpFn(this.listCheck[index].id, 0, this.listCheck[index].content)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length === 1) {
        this.gotoExcelHttpFn(this.listCheck[index].id, this.agentList[0].id, this.listCheck[index].content)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length > 1) {
        this.quectionType = 2;
        this.quectionOption = JSON.stringify({id: this.listCheck[index].id, content: this.listCheck[index].content})
        this.agentListVisible = true
      }
      if (type === 3) {
        this.gotoExcelHttpFn(index, class_id, content)
      }
    },
    gotoExcelHttpFn(id, option, content) {
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/${this.api.task.excel}?id=${id}&class_id=${option}`,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                this.fileDownload(response.data, content)
              }.bind(this)
          )
          .catch(
              function (error) {
                alert(`网络请求出错,${error}`)
              }
          )
    },
    // 单个选项
    gotoExcelOnly(line, id, title, type, class_id) {
      console.log('内容信息：', line, id, title)
      if (type === 1) {
        this.gotoExcelOnlyFn(line, id, title, 0)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length === 1) {
        this.gotoExcelOnlyFn(line, id, title, this.agentList[0].id)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length > 1) {
        this.quectionType = 3;
        this.quectionOption = JSON.stringify({line: line, id: id, title: title})
        this.agentListVisible = true
      }
      if (type === 3) {
        let data_ = JSON.parse(this.quectionOption)
        this.gotoExcelOnlyFn(data_.line, data_.id, data_.title, class_id)
      }
    },
    gotoExcelOnlyFn(line, id, title, class_id) {
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/${this.api.task.sign_export}?question_id=${id}&option=${line.index}&class_id=${class_id}`,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                console.log('导出表哥：', response)
                this.fileDownload(response.data, title + ',' + line.index + '.' + line.text)
              }.bind(this)
          )
          .catch(
              function (error) {
                alert('网络请求出错')
              }
          )
    },
    // 选择下载班级回调
    getClassDown(class_id) {
      // 整个题目问卷
      if (this.quectionType === 1) {
        this.gotoExcelAll(3, class_id)
      }
      // 单个题目
      if (this.quectionType === 2) {
        let data_ = JSON.parse(this.quectionOption)
        this.gotoExcel(data_.id, 3, class_id, data_.content)
      }
      // 单个选项
      if (this.quectionType === 3) {
        let data_ = JSON.parse(this.quectionOption)
        this.gotoExcelOnly(data_.line, data_.id, data_.title, 3, class_id)
      }
    },
    // 导出本题所有答案
    gotoExcelAll(type, class_id) {
      // type 1 所有 2 班级
      if (type === 1) {
        this.getExcelDownFn(0)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length === 1) {
        this.getExcelDownFn(this.agentList[0].id)
      }
      if (type === 2 && this.showDownStatus && this.agentList.length > 1) {
        this.quectionType = 1
        this.agentListVisible = true
      }
      if (type === 3) {
        this.getExcelDownFn(class_id)
      }
    },
    getExcelDownFn(option) {
      this.$http({
        method: 'get',
        url:  `${this.$BASE_URL}/admin/questionnaire_export/index?id=` + this.detailId + '&class_id=' + option,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                this.fileDownload(response.data, '调查问卷明细')
              }.bind(this)
          )
          .catch(
              function (error) {
                alert('网络请求出错')
              }
          )
    },
    fileDownload(data, pushname) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = pushname + '-填写明细.xls' || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    },
    clearFn() {
      this.infoForm = {
        body: [{
          'content': null,
          'type': '1',
          'show_status': 0,
          'option': [{text: '', type: '2', is_commitment: '0'}]
        }],
        title: '',
        class_id: '',
        section_id: '',
        type: 0,
        description: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        student_id: 0,
        commitment: '' // 承诺书
      }
      this.agentList = [];
      this.showDownStatus = false
      this.editBody = null
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {
  }
}
</script>
<style scoped>

#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 80%;
  height: 94%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 30px;
  flex: 1;
  overflow-y: auto;
  /*background: #eee;*/
}

.close-Btn-line {
  cursor: pointer;
}

.jobTime span {
  padding: 0 10px;
}

.task-box {
  background: #fff;
  border-radius: 5px;
  margin-bottom: 10px;
  padding: 20px;
}

.task-box-title {
  border-left: 3px solid #009bfb;
  padding-left: 10px;
  height: 15px;
  line-height: 15px;
}

.task-line-list {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.task-detail-title {
  display: block;
  width: 75px;
}

.task-box-detail {
  margin-top: 20px;
}

.file-link {
  color: #1b8de5;
  cursor: pointer;
}

.file-link:hover {
  text-decoration: underline;
}

.task-status {
  color: red;
}

.task_file_list {
  text-align: center;
  color: #999;
}
</style>
